// pages/addAddr/index.js
var util = require('../../utils/util.js');
var ajax = require('../../utils/ajax.js');
var common = require('../../utils/common.js');
var PageBase = require('../../common/PageBase.js');
var app = getApp();

Page(common.extendPage(PageBase, {
  data: {
    region: ['北京市', '北京市', '东城区'],
    userName: '',
    userPhone: '',
    address: ''
  },
  onLoad(options) {
    this._options = options;

    console.log(this._options.region);

    console.log(this._options);
    if (JSON.stringify(this._options) != "{}") {
      this.setData({
        region: this._options.region.split(','),
        userName: this._options.userName,
        userPhone: this._options.userPhone,
        address: this._options.address
      })
      console.log(this.data.region);
    }

  },
  onShow() {
    if (app.getSid()) { //已登录
    }
  },
  /**
   * 地区切换
   */
  bindRegionChange: function(e) {
    this.setData({
      region: e.detail.value
    })
  },
  /**
   * 提交地址信息
   */
  _submit(evt) {
    if (this._validate(evt.detail.value)) {
      var {
        userName,
        userPhone,
        userAddr
      } = evt.detail.value;
      var paramsUrl = JSON.stringify(this._options) != '{}' ? '/public/api/user/editaddres' : '/public/api/user/addaddres';
      var area = this.data.region.join('/');
      console.log(area);
      var parmasData = {
        uid: wx.getStorageSync('uid'),
        username: userName,
        mobile: userPhone,
        area: area,
        address: userAddr
      }
      if (JSON.stringify(this._options) != '{}') {
        parmasData.id = Number(this._options.addrId)
      }
      ajax.P({
        url: paramsUrl,
        data: parmasData,
        success: (res) => {
          util.tips('修改成功', () => {
            wx.navigateBack();
          })
        },
        fail: (res, isTips) => {
          if (res.message == '失败') {
            util.tips('修改地址失败');
          }
        },
        isTips: true
      })
    }
  },
  /**
   * 验证输入信息
   */
  _validate(value) {
    const {
      userName,
      userPhone,
      userAddr
    } = value;
    const region = this.data.region;
    if (!userName) {
      util.tips('用户姓名不能为空！');
      return false;
    } else if (!userPhone) {
      util.tips('联系电话不能为空');
      return false;
    } else if (!userAddr) {
      util.tips('详细地址不能为空');
      return false;
    }
    return true;
  }
}));